﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace bookshop
{
    public partial class Billing2 : Form
    {
        public Billing2()
        {
            InitializeComponent();
            populate();
        }

        SqlConnection Con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\C#\MyProject\BookShopDb.mdf;Integrated Security=True;Connect Timeout=30;Encrypt=False;");

        private void populate()
        {
            Con.Open();
            string query = "select BillId,Btitle,Qty,Amount, " +
                "case when State=1 then '已收货' else '未收货' end as State " +
                "from BillTb1 where UId=@id";
            SqlCommand cmd = new SqlCommand(query, Con);
            cmd.Parameters.AddWithValue("@id", login.UserId);
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            BillDGV.DataSource = dt;


            //SqlDataAdapter sda = new SqlDataAdapter(query, Con);
            //SqlCommandBuilder scb = new SqlCommandBuilder(sda);
            //var ds = new DataSet();
            //sda.Fill(ds);
            //BillDGV.DataSource = ds.Tables[0];
            Con.Close();
        }

        private void label9_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        private void Billing2_Load(object sender, EventArgs e)
        {
            UserNameLbl.Text = login.UserName;
            foreach (Control c in panel3.Controls)
            {
                c.MouseClick += (s, e2) => panel3_MouseClick(panel3, e2);
            }
            foreach (Control c in panel5.Controls)
            {
                c.MouseClick += (s, e2) => panel5_MouseClick(panel5, e2);
            }
        }

        private void BillDGV_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            BillIdTb.Text = BillDGV.SelectedRows[0].Cells[0].Value.ToString();
            BTitleTb.Text = BillDGV.SelectedRows[0].Cells[1].Value.ToString();
            QtyTb.Text = BillDGV.SelectedRows[0].Cells[2].Value.ToString();
            AmountTb.Text = BillDGV.SelectedRows[0].Cells[3].Value.ToString();
        }

        private void SureBtn_Click(object sender, EventArgs e)
        {
            if (BillIdTb.Text == "" || BTitleTb.Text == "" || QtyTb.Text == "" || AmountTb.Text == "")
            {
                MessageBox.Show("请选择要确认的订单！");
            }
            else
            {
                try
                {
                    string query = "update BillTb1 set State=1 where BillId=@BillId";
                    Con.Open();
                    SqlCommand cmd = new SqlCommand(query, Con);
                    cmd.Parameters.AddWithValue("@BillId", BillIdTb.Text);
                    cmd.ExecuteNonQuery();
                    MessageBox.Show("订单已确认收货！");
                    Con.Close();
                }
                catch (Exception Ex)
                {
                    MessageBox.Show("确认收货失败！" + Ex.Message);
                }
                finally
                {
                    if (Con.State == ConnectionState.Open)
                    {
                        Con.Close();
                    }
                    populate();
                }

            }
        }

        private void Reset()
        {
            BillIdTb.Text = "";
            BTitleTb.Text = "";
            QtyTb.Text = "";
            AmountTb.Text = "";
        }

        private void DelBtn_Click(object sender, EventArgs e)
        {
            if (BillIdTb.Text == "")
            {
                MessageBox.Show("请选择要删除的订单！");
            }
            else
            {
                try
                {
                    string query = "delete from BillTb1 where BillId=@BillId";
                    Con.Open();
                    SqlCommand cmd = new SqlCommand(query, Con);
                    cmd.Parameters.AddWithValue("@BillId", BillIdTb.Text);
                    cmd.ExecuteNonQuery();
                    MessageBox.Show("订单已删除！");
                    Con.Close();
                }
                catch (Exception Ex)
                {
                    MessageBox.Show("订单删除失败！" + Ex.Message);
                }
                finally
                {
                    if (Con.State == ConnectionState.Open)
                    {
                        Con.Close();
                    }
                }
                Reset();
                populate();
            }
        }

        private void PrintBtn_Click(object sender, EventArgs e)
        {
            printPreviewDialog1.Document = printDocument1;
            printDocument1.DefaultPageSettings.PaperSize = new System.Drawing.Printing.PaperSize("pprnm", 285, 600);// 设置纸张大小及名称
            if (printPreviewDialog1.ShowDialog() == DialogResult.OK)
            {
                printDocument1.Print();
            }
        }

        string prodid, prodqty, prodtotal, prodname;//商品名称

        int pos = 60;//id,数量,小计,打印坐标

        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            try
            {
                decimal totalsum = 0;
                e.Graphics.DrawString("劳瓦尼书店", new Font("隶书", 12, FontStyle.Bold), Brushes.Red, new Point(100));
                e.Graphics.DrawString("商品编号  商品名称  数量  总计", new Font("楷体", 10, FontStyle.Bold), Brushes.Red, new Point(36, 40));
                foreach (DataGridViewRow row in BillDGV.Rows)
                {
                    if (row.IsNewRow) continue;        // 跳过自动新增的空行

                    prodid = row.Cells[0].Value?.ToString() ?? "";
                    prodname = row.Cells[1].Value?.ToString() ?? "";
                    prodqty = row.Cells[2].Value?.ToString() ?? "0";
                    prodtotal = row.Cells[3].Value?.ToString() ?? "0";

                    decimal.TryParse(prodtotal, out decimal lineTotal);
                    totalsum += lineTotal;// 累计总额
                    e.Graphics.DrawString(prodid, new Font("楷体", 8, FontStyle.Bold), Brushes.Blue, new Point(52, pos));
                    e.Graphics.DrawString(prodname, new Font("楷体", 8, FontStyle.Bold), Brushes.Blue, new Point(115, pos));
                    e.Graphics.DrawString(prodqty, new Font("楷体", 8, FontStyle.Bold), Brushes.Blue, new Point(190, pos));
                    e.Graphics.DrawString(lineTotal.ToString(), new Font("楷体", 8, FontStyle.Bold), Brushes.Blue, new Point(223, pos));
                    pos = pos + 20;// 更新打印坐标

                }
                e.Graphics.DrawString("订单总额：￥" + totalsum.ToString(), new Font("楷体", 12, FontStyle.Bold), Brushes.Crimson, new Point(60, pos + 50));
                e.Graphics.DrawString("*********劳瓦尼书店*********", new Font("楷体", 10, FontStyle.Bold), Brushes.Crimson, new Point(40, pos + 85));
                pos = 60; // 重置打印坐标
                totalsum = 0; // 重置总额
            }
            catch (Exception ex)
            {
                MessageBox.Show("打印出错：\n" + ex.Message + "\n" + ex.StackTrace);
            }

        }

        private void panel3_MouseClick(object sender, MouseEventArgs e)
        {
            this.Hide();
            Billing obj = new Billing();
            obj.Show();
        }
        private void panel5_MouseClick(object sender, MouseEventArgs e)
        {
            this.Hide();
            login obj = new login();
            obj.Show();
        }
    }
}
